package com.ruoyi.quartz.service.impl;

import com.bocsoft.udp.t_del.TDel;
import com.bocsoft.udp.t_del.entity.Const;
import com.bocsoft.udp.t_del.entity.TableRule;
import com.bocsoft.udp.t_del.entity.TableTask;
import com.bocsoft.udp.t_del.tdel.MySQLTDel;
import com.bocsoft.udp.t_del.tdel.face.ITDel;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.quartz.controller.SysJobMyController;
import com.ruoyi.quartz.domain.SysDeptImport;
import com.ruoyi.quartz.domain.SysUserImport;
import com.ruoyi.quartz.mapper.SysJobMyMapper;
import com.ruoyi.quartz.service.ISysJobMyService;
import org.quartz.SchedulerException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 定时任务调度信息 服务层
 *
 * @author bocgx
 */
@Service
public class SysJobMyServiceImpl implements ISysJobMyService {

    private final static Logger logger = LoggerFactory.getLogger(ISysJobMyService.class);

    @Value("${spring.datasource.druid.master.password}")
    private  String masterPassword;

    @Value("${spring.datasource.druid.slave.password}")
    private  String slavePassword;

    @Value("${ruoyi.ftpPath}")
    private String ftpPath;

    @Autowired
    private SysJobMyMapper sysJobMyMapper;


    /**
     * 新增调度任务信息加载文件更新机构及用户
     *
     * @param
     * @return 结果
     */
    @Override
    //@Transactional(rollbackFor = Exception.class)
    public void updateDeptAndUser() throws SchedulerException, TaskException {

            sysJobMyMapper.updateDeptAndUser();
    }

    @Override
    public void extractAndLoadSysDeptTableTask() throws SchedulerException, TaskException {
        String currDate = DateUtils.dateTime();
        TDel tDel = new TDel(currDate);
        TableRule tableRule = new TableRule();
        tableRule.setIpAddress("127.0.0.1");
        tableRule.setPort("3306");
        tableRule.setUser("root");
        tableRule.setPassword(masterPassword);
        tableRule.setDataBaseName("boc_admin");
        tableRule.setTabName("sys_dept");
        tableRule.setColumns("dept_id,dept_code,parent_code,parent_id,ancestors,superiors,dept_name,order_num,leader,phone,email,org_lvl,org_idr,org_tp_code,STATUS,del_flag,create_by,create_time,update_by,update_time");
        tableRule.setAssemblyID("BocAdmin001"); // 组件编号
        tableRule.setPlatformID("P8"); // 14
        tableRule.setSep("\\u0001 |\\u0001"); // 15
        tableRule.setCycFlag("D"); // 16
        tableRule.setIncID("0"); // 17
        tableRule.setTableGenType("1"); // 18
        tableRule.setFileFormat(Const.FILE_FORMAT_P6);
        tableRule.setIsSplitFlag("0");
        tableRule.setMechanismID("000001");
        tableRule.setFileNamePrefix("BOC.ADMIN.SYSDEPT");
        tableRule.setFileDir("D://filesIn");
        // 抽取表数据
        TableTask extractTask = tDel.extractTableTask(tableRule);
        System.out.println(extractTask);
        //return extractTask.getResult();
        if(extractTask.getResult()){
            ITDel loadDel = new MySQLTDel();
            // 设置表配置
            tableRule.setIpAddress("127.0.0.1");
            tableRule.setPort("3306");
            tableRule.setUser("root");
            tableRule.setPassword(slavePassword);
            tableRule.setDataBaseName("test");
            tableRule.setTabName("sys_dept");
            tableRule.setTableFilePath("D://filesIn//BOC.ADMIN.SYSDEPT."+currDate+"0");
            tableRule.setMetadataFilePath("D://filesIn//BOC.ADMIN.SYSDEPT."+currDate+"0"+".TABLEMETADATA");
            // 抽取表数据
            TableTask loadTask = loadDel.loadTableTask(tableRule);
            System.out.println(loadTask);
            System.out.println(loadTask.getErrorCodeEnum());
            System.out.println(loadTask.getSuccessRecNum());  //成功数据行数
            System.out.println(loadTask.getErrorRecNum()); //错误数据行数
        }
    }

    @Override
    public void extractAndLoadSysUserTableTask() throws SchedulerException, TaskException {
        String currDate = DateUtils.dateTime();
        TDel tDel = new TDel(currDate);
        TableRule tableRule = new TableRule();
        tableRule.setIpAddress("127.0.0.1");
        tableRule.setPort("3306");
        tableRule.setUser("root");
        tableRule.setPassword(masterPassword);
        tableRule.setDataBaseName("boc_admin");
        tableRule.setTabName("sys_user");
        tableRule.setColumns("user_id,dept_id,user_name,nick_name,user_type,email,phonenumber,sex,avatar,password,status,del_flag,login_ip,login_date,create_by,create_time,update_by,update_time,remark");
        tableRule.setAssemblyID("BocAdmin001"); // 组件编号
        tableRule.setPlatformID("P8"); // 14
        tableRule.setSep("\\u0001 |\\u0001"); // 15
        tableRule.setCycFlag("D"); // 16
        tableRule.setIncID("0"); // 17
        tableRule.setTableGenType("1"); // 18
        tableRule.setFileFormat(Const.FILE_FORMAT_P6);
        tableRule.setIsSplitFlag("0");
        tableRule.setMechanismID("000001");
        tableRule.setFileNamePrefix("BOC.ADMIN.SYSUSER");
        tableRule.setFileDir("D://filesIn");
        // 抽取表数据
        TableTask extractTask = tDel.extractTableTask(tableRule);
        System.out.println(extractTask);
        //return extractTask.getResult();
        if(extractTask.getResult()){
            ITDel loadDel = new MySQLTDel();
            // 设置表配置
            tableRule.setIpAddress("127.0.0.1");
            tableRule.setPort("3306");
            tableRule.setUser("root");
            tableRule.setPassword(slavePassword);
            tableRule.setDataBaseName("test");
            tableRule.setTabName("sys_user");
            tableRule.setTableFilePath("D://filesIn//BOC.ADMIN.SYSUSER."+currDate+"0");
            tableRule.setMetadataFilePath("D://filesIn//BOC.ADMIN.SYSUSER."+currDate+"0"+".TABLEMETADATA");
            // 抽取表数据
            TableTask loadTask = loadDel.loadTableTask(tableRule);
            System.out.println(loadTask);
            System.out.println(loadTask.getErrorCodeEnum());
            System.out.println(loadTask.getSuccessRecNum());  //成功数据行数
            System.out.println(loadTask.getErrorRecNum()); //错误数据行数
        }
    }

    @Override
    public void extractAndLoadSysRoleDeptTableTask() throws SchedulerException, TaskException {
        String currDate = DateUtils.dateTime();
        TDel tDel = new TDel(currDate);
        TableRule tableRule = new TableRule();
        tableRule.setIpAddress("127.0.0.1");
        tableRule.setPort("3306");
        tableRule.setUser("root");
        tableRule.setPassword(masterPassword);
        tableRule.setDataBaseName("boc_admin");
        tableRule.setTabName("sys_role_dept");
        tableRule.setColumns("role_id,dept_id");
        tableRule.setAssemblyID("BocAdmin001"); // 组件编号
        tableRule.setPlatformID("P8"); // 14
        tableRule.setSep("\\u0001 |\\u0001"); // 15
        tableRule.setCycFlag("D"); // 16
        tableRule.setIncID("0"); // 17
        tableRule.setTableGenType("1"); // 18
        tableRule.setFileFormat(Const.FILE_FORMAT_P6);
        tableRule.setIsSplitFlag("0");
        tableRule.setMechanismID("000001");
        tableRule.setFileNamePrefix("BOC.ADMIN.SYSROLEDEPT");
        tableRule.setFileDir("D://filesIn");
        // 抽取表数据
        TableTask extractTask = tDel.extractTableTask(tableRule);
        System.out.println(extractTask);
        //return extractTask.getResult();
        if(extractTask.getResult()){
            ITDel loadDel = new MySQLTDel();
            // 设置表配置
            tableRule.setIpAddress("127.0.0.1");
            tableRule.setPort("3306");
            tableRule.setUser("root");
            tableRule.setPassword(slavePassword);
            tableRule.setDataBaseName("test");
            tableRule.setTabName("sys_role_dept");
            tableRule.setTableFilePath("D://filesIn//BOC.ADMIN.SYSROLEDEPT."+currDate+"0");
            tableRule.setMetadataFilePath("D://filesIn//BOC.ADMIN.SYSROLEDEPT."+currDate+"0"+".TABLEMETADATA");
            // 抽取表数据
            TableTask loadTask = loadDel.loadTableTask(tableRule);
            System.out.println(loadTask);
            System.out.println(loadTask.getErrorCodeEnum());
            System.out.println(loadTask.getSuccessRecNum());  //成功数据行数
            System.out.println(loadTask.getErrorRecNum()); //错误数据行数
        }
    }

    @Override
    public int batchDeptImport() throws IOException {
        List<SysDeptImport> deptImportList = new ArrayList<SysDeptImport>();
        String filePath = ftpPath+"/o_cinm_boc_org_hier_w.txt"; // 文本文件路径
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 假设每行数据由逗号分隔
                String[] fields = line.split("\\s+\\|\\s+");
                if (fields.length == 10) {
                    SysDeptImport sysDeptImport = new SysDeptImport();
                    sysDeptImport.setDeptCode(fields[0].trim());
                    sysDeptImport.setParentCode(fields[1].trim());
                    sysDeptImport.setDeptName(fields[2].trim());
                    sysDeptImport.setOrgLvl(fields[3].trim());
                    sysDeptImport.setOrgIdr(fields[4].trim());
                    sysDeptImport.setOrgTpCode(fields[5].trim());
                    sysDeptImport.setCreateBy(fields[6].trim());
                    sysDeptImport.setCreateTime(dateFormat(fields[7].trim()));
                    sysDeptImport.setUpdateBy(fields[8].trim());
                    sysDeptImport.setUpdateTime(dateFormat(fields[9].trim()));
                    deptImportList.add(sysDeptImport);
                }
            }
        }
        return sysJobMyMapper.batchDeptImport(deptImportList);
    }

    @Override
    public int batchUserImport() throws IOException {
        List<SysUserImport> userImportList = new ArrayList<SysUserImport>();
        String filePath = ftpPath+"/o_chrm_tbl_employee_info_w.txt"; // 文本文件路径
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 假设每行数据由逗号分隔
                String[] fields = line.split("\\s+\\|\\s+");
                if (fields.length == 9) {
                    SysUserImport userImport = new SysUserImport();
                    userImport.setDeptId(fields[0].trim());
                    userImport.setUserName(fields[1].trim());
                    userImport.setNickName(fields[2].trim());
                    userImport.setSex(fields[3].trim());
                    userImport.setStatus(fields[4].trim());
                    userImport.setCreateBy(fields[5].trim());
                    userImport.setCreateTime(dateFormat(fields[6].trim()));
                    userImport.setUpdateBy(fields[7].trim());
                    userImport.setUpdateTime(dateFormat(fields[8].trim()));
                    userImportList.add(userImport);
                }
            }
        }
        return sysJobMyMapper.batchUserImport(userImportList);
    }

    public Date dateFormat(String dateString){
        Date date = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            dateString = dateString.replace("\\","");
            date = formatter.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    @Override
    public void extractTableTaskByXML() throws SchedulerException, TaskException {
        TDel tDel = new TDel("20241107");
        tDel.startBatchDataExtractByXml("D:/filesIn/data_conf.xml");
    }
}
